package com.nowcoder.community.util;

import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.mail.javamail.MimeMessageHelper;
import org.springframework.stereotype.Component;

import javax.mail.MessagingException;
import javax.mail.internet.MimeMessage;

/**
 * @author 花木凋零成兰
 * @date 2024/3/7 19:40
 */
@Component      // 让Spring容器管理Bean
@Slf4j(topic = "MailClient.class")
public class MailClient {

    @Autowired
    private JavaMailSender mailSender;

    @Value("${spring.mail.username}")   // 将配置文件信息注入到当前Bean
    private String from;

    public void sendMail(String to, String subject, String content) {
        try {
            MimeMessage message = mailSender.createMimeMessage();
            MimeMessageHelper messageHelper = new MimeMessageHelper(message);
            messageHelper.setFrom(from);    // 设置发件人
            messageHelper.setTo(to);        // 设置收件人
            messageHelper.setSubject(subject);  // 设置邮件主题
            messageHelper.setText(content, true);   // true 表示内容允许支持html文件
            mailSender.send(messageHelper.getMimeMessage());
        } catch (MessagingException e) {
            log.error("发送邮件失败：" + e.getMessage());
        }
    }

}
